class ProjectsController < ApplicationController
  # GET /projects
  # GET /projects.xml
  def index
    @projects = current_user.projects
    
    @logs = Log.all(:conditions => {:project_id => @projects}, 
                    :order => "created_at DESC",
                    :limit => 15)
                    
    @late_milestones = Milestone.late.all(:conditions => {:project_id => @projects})
    
    @my_activities = current_user.activities.open(:order => "project_id")
  end

  # GET /projects/1
  # GET /projects/1.xml
  def show
    @project = current_user.projects.find(params[:id])
    @late_milestones = @project.milestones.late
    @my_activities = current_user.activities.open(:conditions => {:project_id => @project.id})
  end

  # GET /projects/new
  # GET /projects/new.xml
  def new
    @project = current_user.projects.new
  end

  # GET /projects/1/edit
  def edit
    @project = current_user.projects.find(params[:id])
  end

  # POST /projects
  # POST /projects.xml
  def create 
    @project = current_user.projects.new(params[:project])
    @project.owner = current_user
    
    if @project.save
      flash[:success] = :project_successfully_created
      
      @project.designations.new(:user => current_user, :admin => 1).save
      
      redirect_to @project
    else
      render :action => "new"
    end
  end

  # PUT /projects/1
  # PUT /projects/1.xml
  def update
    @project = current_user.projects.find(params[:id])

    respond_to do |format|
      if @project.update_attributes(params[:project])
        flash[:notice] = 'Project was successfully updated.'
        format.html { redirect_to(@project) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @project.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /projects/1
  # DELETE /projects/1.xml
  def destroy
    @project = current_user.projects.find(params[:id])
    @project.destroy

    respond_to do |format|
      format.html { redirect_to(projects_url) }
      format.xml  { head :ok }
    end
  end
end
